<template>
  <div class="admin-container">
    <!-- 登录页面 -->
    <div v-if="!isLoggedIn" class="login-container">
      <el-card class="login-card">
        <div class="login-title">{{ loginType === 'admin' ? '管理员登录' : '企业登录' }}</div>
        <div class="login-type-switch">
          <el-radio-group v-model="loginType" size="medium">
            <el-radio-button label="admin">管理员登录</el-radio-button>
            <el-radio-button label="company">企业登录</el-radio-button>
          </el-radio-group>
        </div>
        <!-- 管理员登录表单 -->
        <el-form v-if="loginType === 'admin'" :model="loginForm" :rules="loginRules" ref="loginForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入管理员用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
          </el-form-item>
        </el-form>
        <!-- 企业登录表单 -->
        <el-form v-else :model="loginForm" :rules="loginRules" ref="loginForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入企业用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
          </el-form-item>
        </el-form>
        <el-button v-if="loginType === 'company'" type="text" class="register-btn" @click="showCompanyRegister">
          <i class="el-icon-office-building"></i> 企业注册
        </el-button>
      </el-card>
    </div>

    <!-- 后台管理页面 -->
    <div v-else class="admin-content">
      <!-- 顶部导航栏 -->
      <el-header class="admin-header" v-if="!isAdminRoute">
        <div class="header-left">
          <h2>网络招聘平台管理系统</h2>
        </div>
        <div class="header-right">
          <span class="admin-name">{{ adminInfo.role === 'admin' ? '管理员' : '企业' }}：{{ adminInfo.username }}</span>
          <el-button type="text" @click="handleLogout">退出登录</el-button>
        </div>
      </el-header>

      <!-- 主体内容区 -->
      <el-container class="admin-container">
        <!-- 左侧菜单 -->
        <el-aside width="200px">
          <el-menu :default-active="activeMenu" class="admin-menu" background-color="#304156" text-color="#fff"
            active-text-color="#409EFF" router>
            <!-- 管理员菜单 -->
            <template v-if="adminInfo.role === 'admin'">
              <el-menu-item index="/admin/user">
                <i class="el-icon-user"></i>
                <span>用户管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/company">
                <i class="el-icon-office-building"></i>
                <span>公司管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/job-examine">
                <i class="el-icon-suitcase"></i>
                <span>职位审核</span>
              </el-menu-item>
              <el-menu-item index="/admin/notice">
                <i class="el-icon-s-flag"></i>
                <span>公告管理</span>
              </el-menu-item>
            </template>
            <!-- 企业菜单 -->
            <template v-else>
              <el-menu-item index="/admin/job">
                <i class="el-icon-suitcase"></i>
                <span>职位管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/deliver">
                <i class="el-icon-document"></i>
                <span>投递管理</span>
              </el-menu-item>
            </template>
          </el-menu>
        </el-aside>

        <!-- 右侧内容区 -->
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </div>

    <!-- 企业注册对话框 -->
    <el-dialog title="企业注册" :visible.sync="registerDialogVisible" width="600px" custom-class="register-dialog"
      :close-on-click-modal="false">
      <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="100px"
        class="register-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"
            prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input v-model="registerForm.password2" type="password" placeholder="请再次输入密码"
            prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="registerForm.companyName" placeholder="请输入企业名称"
            prefix-icon="el-icon-office-building"></el-input>
        </el-form-item>
        <el-form-item label="企业地址" prop="companyAddress">
          <el-input v-model="registerForm.companyAddress" placeholder="请输入企业地址"
            prefix-icon="el-icon-location"></el-input>
        </el-form-item>
        <el-form-item label="企业头像" prop="companyAvatar">
          <MyUpload ref="childUpload" @callParent="transDownloadUrl"></MyUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="registerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCompanyRegister" :loading="registerLoading">注 册</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLogin, getRegister } from '@/api';
import MyUpload from '@/components/upload';


export default {
  name: 'Admin',
  components: {
    MyUpload
  },
  data() {
    // 密码验证规则
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      isLoggedIn: false,
      loginType: 'admin', // 新增登录类型
      adminInfo: {
        username: '',
        role: ''
      },
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      },
      activeMenu: '', // 修改默认值为空
      // 企业注册相关数据
      registerDialogVisible: false,
      registerLoading: false,
      registerForm: {
        username: '',
        password: '',
        password2: '',
        type: 2, // 2表示企业用户
        companyName: '',
        companyAddress: '',
        companyAvatar: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        password2: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
        companyName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        companyAddress: [
          { required: true, message: '请输入企业地址', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    isAdminRoute() {
      return this.$route.path === '/admin';
    }
  },
  created() {
    // 检查是否已登录
    const adminInfo = localStorage.getItem('adminInfo');
    if (adminInfo) {
      this.isLoggedIn = true;
      this.adminInfo = JSON.parse(adminInfo);
      // 根据角色设置默认菜单
      this.activeMenu = this.adminInfo.role === 'admin' ? '/admin/user' : '/admin/job';
    }
  },
  methods: {
    transDownloadUrl(url) {
      this.registerForm.companyAvatar = url;
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 调用登录接口
          getLogin({
            username: this.loginForm.username,
            password: this.loginForm.password,
            type: this.loginType === 'admin' ? 3 : 2 
          }).then(res => {
            // 登录成功
            this.adminInfo = {
              username: this.loginForm.username,
              role: this.loginType
            };
            localStorage.setItem('token', res.data.token);
            localStorage.setItem('adminInfo', JSON.stringify(this.adminInfo));
            // 根据角色设置默认菜单
            console.log(this.loginType == 'admin');
            this.activeMenu = this.loginType == 'admin' ? '/admin/user' : '/admin/job';
            console.log(this.activeMenu);
            this.$message.success('登录成功');
            setTimeout(() => {
              this.isLoggedIn = true;
            }, 1000);

            // 清空表单
            this.$refs.loginForm.resetFields();
          }).catch(err => {
            this.$message.error(err.msg || '登录失败');
          });
        } else {
          return false;
        }
      });
    },
    handleLogout() {
      // 清除登录信息
      localStorage.removeItem('adminInfo');
      this.isLoggedIn = false;
      this.adminInfo = {
        username: '',
        role: ''
      };
      this.$message.success('已退出登录');
    },
    showCompanyRegister() {
      this.registerDialogVisible = true;
      this.registerForm = {
        username: '',
        password: '',
        password2: '',
        type: 2,
        companyName: '',
        companyAddress: '',
        companyAvatar: ''
      };
    },
    handleCompanyRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.registerLoading = true;
          this.registerForm.type = 2;
          getRegister(this.registerForm).then(res => {
            this.$message.success('注册成功，请登录');
            this.loading = false;
            this.registerDialogVisible = false;
            this.registerLoading = false;
            this.$refs.registerForm.resetFields();
          }).catch(err => {
            this.$message.error(err.msg);
            this.loading = false;
          })
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.registerForm.companyAvatar = res.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>

<style scoped>
.admin-container {
  height: 100vh;
  background-color: #f0f2f5;
}

/* 登录页面样式 */
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
  position: relative;
}

.login-card {
  position: relative;
  z-index: 2;
  width: 420px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: #f0f2f5;
  overflow: hidden;
}

.login-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #303133;
  position: relative;
  z-index: 1;
}

:deep(.el-form) {
  position: relative;
  z-index: 1;
}

/* 登录类型切换样式 */
.login-type-switch {
  text-align: center;
  margin-bottom: 30px;
}

:deep(.el-radio-button__inner) {
  padding: 12px 24px;
  font-size: 14px;
  transition: all 0.3s;
}

:deep(.el-radio-button__inner:hover) {
  color: #409EFF;
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #409EFF;
  border-color: #409EFF;
  box-shadow: -1px 0 0 0 #409EFF;
}

/* 后台管理页面样式 */
.admin-header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 60px;
}

.header-left h2 {
  font-size: 20px;
  color: #303133;
  margin: 0;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.admin-name {
  color: #606266;
  font-size: 14px;
}

.admin-menu {
  height: 100%;
  border-right: none;
  background-color: #304156;
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  transition: all 0.3s;
}

:deep(.el-menu-item:hover) {
  background-color: #263445 !important;
}

:deep(.el-menu-item.is-active) {
  background-color: #263445 !important;
  border-right: 3px solid #409EFF;
}

.el-aside {
  background-color: #304156;
  transition: width 0.3s;
}

.el-main {
  background-color: #f0f2f5;
  padding: 24px;
  overflow-y: auto;
}

/* 注册按钮样式 */
.register-btn {
  width: 100%;
  color: #409EFF;
  font-size: 14px;
  transition: all 0.3s;
  text-align: right;
  margin-top: 20px;
  padding: 10px 0;
}

.register-btn:hover {
  color: #66b1ff;
  transform: translateY(-1px);
}

.register-btn i {
  margin-right: 5px;
}

/* 注册对话框样式 */
:deep(.register-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.register-dialog .el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

:deep(.register-dialog .el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.register-dialog .el-dialog__body) {
  padding: 30px 24px;
}

:deep(.register-dialog .el-dialog__footer) {
  padding: 20px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

:deep(.register-form .el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.register-form .el-input__inner) {
  border-radius: 4px;
  transition: all 0.3s;
}

:deep(.register-form .el-input__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.dialog-footer .el-button) {
  padding: 12px 25px;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

:deep(.dialog-footer .el-button--primary) {
  background-color: #409EFF;
  border-color: #409EFF;
}

:deep(.dialog-footer .el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .login-card {
    width: 90%;
    margin: 0 20px;
  }
  
  .admin-header {
    padding: 0 16px;
  }
  
  .header-left h2 {
    font-size: 18px;
  }
  
  .el-main {
    padding: 16px;
  }
}
</style>